﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using SpCop.Core.Model;
using SpCop.Model;

namespace SpCop.Localization
{
    public class ResourceStringsAreValid : RuleBase
    {

        static Regex expression = new Regex("^\\$Resources\\:.+\\,.+;$", RegexOptions.Compiled);
        private IList<Problem> _problems;

        public override IList<Problem> Check(Package package)
        {

            _problems = base.Check(package);
            Visit(package);



            return _problems;
        }

        public override void Visit(Element item)
        {
            if (item.ElementType == ElementType.Field)
            {
                var title = GetValueOrEmpty(item.Xml, "DisplayName");
                var description = GetValueOrEmpty(item.Xml, "Description");
                var group = GetValueOrEmpty(item.Xml, "Group");

                if (!string.IsNullOrEmpty(title) && !expression.IsMatch(title))
                {
                    AddProblem("AttributeValueNotAResourceString", "Title", item.ElementType.ToString(), group, item.Feature.Folder);
                }

                if (!string.IsNullOrEmpty(description) && !expression.IsMatch(description))
                {
                    AddProblem("AttributeValueNotAResourceString", "Description", item.ElementType.ToString(), group, item.Feature.Folder);
                }
                if (!string.IsNullOrEmpty(group) && !expression.IsMatch(group))
                {
                    AddProblem("AttributeValueNotAResourceString", "Group", item.ElementType.ToString(), group, item.Feature.Folder);
                }

            }

            base.Visit(item);
        }


        public string GetValueOrEmpty(XElement element, string name)
        {
            var att = element.Attribute("DisplayName");

            if (att == null)
                return string.Empty;

            return (string)att;
        }
    }
}

   
